package com.speech.http;

import android.util.Log;

import com.speech.constant.UseContant;
import com.speech.event.MessageEvent;
import com.speech.result.Result;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhangjian
 * 使用Retrofit2 Call异步请求时的回调
 */
public abstract class BaseCallback<T> implements Callback<Result<T>> {

        @Override
        public void onResponse(Call<Result<T>> call, Response<Result<T>> response) {
            Log.e("原始","原始数据onResponse");
            if(response.isSuccessful()){
                Result<T> result = response.body();
                switch (result.getCode()){
                        // 用户未登录/登录过期
                    case UseContant.TOKEN_INVALID:
                        // 登录设备异常
                    case UseContant.LOGIN_DEVICE_ABNORMAL:
                        // 登录信息异常
                    case UseContant.LOGIN_INFO_ABNORMAL:
                        EventBus.getDefault().post(new MessageEvent());
                        break;
                    case UseContant.REQUEST_SUCCESS:
                        onSuccess(result.getData());
                        break;
                    default:
                        onAbnormal(result.getMsg());
                        break;
                }
            }else {
                onAbnormal("错误代码：" + response.code());
            }
        }

        public abstract void onSuccess (T t);

        public abstract void onAbnormal(String msg);

        public abstract void onFailure(String msg);

        @Override
        public void onFailure(Call<Result<T>> call, Throwable t) {
            Log.e("原始","原始数据onFailure");
            onFailure("数据请求异常");
        }
    }
